<!--
 * @Author: Lzx
 * @Date: 2022-04-21 08:20:55
 * @LastEditors: Lzx
 * @LastEditTime: 2022-04-27 21:11:05
 * @FilePath: /web-vue/src/pages/Order/index.vue
 * @Description: 订单中心
-->
<template>
  <div class="app-container">
    <el-row class="data-table row-panel row-panel-first">
      <el-col>
        <el-card>
          <el-row :gutter="0">
            <!-- 【租房订单】参数 -->
            <el-col>
              <el-form :model="queryForm" size="medium" :inline="true">
                <table
                  style="border-collapse: collapse; width: 100%"
                  class="table-common-style"
                >
                  <colgroup>
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                    <col width="11.11%" />
                  </colgroup>
                  <tbody>
                    <tr>
                      <td><div class="form-item-label">预定入住日期：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="orderStartTime">
                          <el-date-picker
                            v-model="queryForm.orderStartTime"
                            :picker-options="DateRange_Picker_Option"
                            type="daterange"
                            align="right"
                            unlink-panels
                            range-separator="——"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy/MM/dd"
                          >
                          </el-date-picker>
                        </el-form-item>
                      </td>
                      <td><div class="form-item-label">预定退房日期：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="orderEndTime">
                          <el-date-picker
                            v-model="queryForm.orderEndTime"
                            :picker-options="DateRange_Picker_Option"
                            type="daterange"
                            align="right"
                            unlink-panels
                            range-separator="——"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy/MM/dd"
                          >
                          </el-date-picker>
                        </el-form-item>
                      </td>
                      <td><div class="form-item-label">我的评分：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="starMark">
                          <el-input
                            v-model.trim="queryForm.starMark"
                            placeholder="请输入查询参数"
                            clearable
                          >
                          </el-input>
                        </el-form-item>
                      </td>
                    </tr>
                    <tr>
                      <td><div class="form-item-label">订单状态：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="orderStatus">
                          <el-select
                            v-model="queryForm.orderStatus"
                            filterable
                            clearable
                            placeholder="请选择查询参数"
                            @change="queryDataBtn()"
                          >
                            <el-option
                              v-for="item in $store.state.DICT
                                .orderStatusSelect"
                              :key="item.code"
                              :label="item.name"
                              :value="item.code"
                            >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </td>
                      <td><div class="form-item-label">创建时间：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="createTime">
                          <el-date-picker
                            v-model="queryForm.createTime"
                            :picker-options="DateRange_Picker_Option"
                            type="daterange"
                            align="right"
                            unlink-panels
                            range-separator="——"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy/MM/dd"
                          >
                          </el-date-picker>
                        </el-form-item>
                      </td>
                      <td><div class="form-item-label">更新时间：</div></td>
                      <td colspan="2">
                        <el-form-item valign="middle" prop="updateTime">
                          <el-date-picker
                            v-model="queryForm.updateTime"
                            :picker-options="DateRange_Picker_Option"
                            type="daterange"
                            align="right"
                            unlink-panels
                            range-separator="——"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy/MM/dd"
                          >
                          </el-date-picker>
                        </el-form-item>
                      </td>
                    </tr>
                    <tr>
                      <td colspan="10">
                        <!-- 按钮 -->
                        <el-form-item>
                          <el-button
                            type="primary"
                            icon="el-icon-search"
                            @click="queryDataBtn()"
                            :loading="requestLoading"
                            >查询
                          </el-button>
                          <el-button
                            icon="el-icon-refresh-left"
                            @click="
                              () =>
                                Object.assign(
                                  this.queryForm,
                                  this.$options.data().queryForm
                                )
                            "
                            >清空查询条件
                          </el-button>
                        </el-form-item>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </el-form>
            </el-col>
            <!-- 【租房订单】信息表 -->
            <el-table :data="tableData" style="width: 100%">
              <el-table-column type="expand">
                <template slot-scope="props">
                  <el-form
                    label-position="left"
                    inline
                    class="demo-table-expand"
                  >
                    <el-form-item label="民宿名称 :">
                      <span v-if="props.row.houseId == 1517133192279879682"
                        >丽江束河古镇民宿客栈
                      </span>
                      <span v-if="props.row.houseId == 1517820305774092289"
                        >曲靖市风景区大客栈
                      </span>
                      <span v-if="props.row.houseId == 1518241241740525570"
                        >一红彬的民宿
                      </span>
                    </el-form-item>
                    <el-form-item label="图片 :">
                      <span v-if="props.row.houseId == 1517133192279879682">
                        <el-image
                          style="
                            border-radius: 20px;
                            width: 100px;
                            height: 100px;
                          "
                          src="http://localhost:8080/image/2022-04/72fa59a0-d58b-4b76-966e-639013d92a44.jpeg"
                          :preview-src-list="testList"
                        >
                        </el-image>
                      </span>
                      <span v-if="props.row.houseId == 1517820305774092289">
                        <el-image
                          style="
                            border-radius: 20px;
                            width: 100px;
                            height: 100px;
                          "
                          src="http://localhost:8080/image/2022-04/09192289-e267-429e-b4ef-2319844526cd.jpeg"
                          :preview-src-list="testList"
                        >
                        </el-image>
                      </span>
                      <span v-if="props.row.houseId == 1518241241740525570">
                        <el-image
                          style="
                            border-radius: 20px;
                            width: 100px;
                            height: 100px;
                          "
                          src="http://localhost:8080/image/2022-04/9c02c2ad-efcc-4f71-b31a-d119464a4800.jpg"
                          :preview-src-list="testList"
                        >
                        </el-image>
                      </span>
                    </el-form-item>
                    <el-form-item label="民宿老板 :">
                      <span v-if="props.row.houseOwner == 30">房东-李大圣</span>
                      <span v-if="props.row.houseOwner == 1">SuperAdmin</span>
                    </el-form-item>
                    <el-form-item label="是否需要餐饮 :">
                      <span v-if="props.row.isNeedMeal == 0">否</span>
                      <span v-if="props.row.isNeedMeal == 1">是</span>
                    </el-form-item>
                    <el-form-item label="餐饮费用 :">
                      <span v-if="props.row.mealCost == null">无</span>
                      <span v-if="props.row.mealCost != null">{{
                        props.row.mealCost
                      }}</span>
                    </el-form-item>
                    <el-form-item label="房费 :">
                      <span>￥{{ props.row.houseCost }}</span>
                    </el-form-item>
                    <el-form-item label="总费用 :">
                      <span>￥{{ props.row.totalCost }}</span>
                    </el-form-item>
                    <el-form-item label="入住天数 :">
                      <span>{{ props.row.housingDay }}天</span>
                    </el-form-item>
                    <el-form-item label="我的评价 :">
                      <span v-if="props.row.appraise == null">无</span>
                      <span v-if="props.row.appraise != null">{{
                        props.row.appraise
                      }}</span>
                    </el-form-item>
                    <el-form-item label="房东回复 :">
                      <span v-if="props.row.reply == null">无</span>
                      <span v-if="props.row.reply != null">{{
                        props.row.reply
                      }}</span>
                    </el-form-item>
                    <el-form-item label="我的评分 :">
                      <el-rate
                        style="margin-top: 12px"
                        v-model="props.row.starMark"
                        show-text
                        text-color="#ff9900"
                        :texts="['差评', '一般般', '不错', '满意', '非常满意']"
                        :colors="{
                          1: '#99A9BF',
                          2: '#f0d186',
                          3: '#f7cb62',
                          4: '#F7BA2A',
                          5: '#FF9900',
                        }"
                        disabled
                      >
                      </el-rate>
                    </el-form-item>
                    <el-form-item label="预定入住日期 :">
                      <span>{{ props.row.orderStartTime }}</span>
                    </el-form-item>
                    <el-form-item label="预定退房日期 :">
                      <span>{{ props.row.orderEndTime }}</span>
                    </el-form-item>
                  </el-form>
                </template>
              </el-table-column>
              <el-table-column label="订单 ID" prop="id"> </el-table-column>
              <el-table-column label="订单创建时间" prop="createTime">
              </el-table-column>
              <el-table-column label="订单状态" prop="orderStatus">
                <template slot-scope="props">
                  <el-tag v-if="props.row.orderStatus == 1" type="warning"
                    >待支付</el-tag
                  >
                  <el-tag v-if="props.row.orderStatus == 2" type="success"
                    >已支付</el-tag
                  >
                  <el-tag v-if="props.row.orderStatus == 5" type="info"
                    >待评价</el-tag
                  >
                  <el-tag v-if="props.row.orderStatus == 6" type="primary "
                    >已评价</el-tag
                  >
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <!-- slot-scope="scope":插槽
                     slot-scope=“scope” //取到当前单元格
                     scope.$index //拿到当前行的index
                     scope.row //拿到当前行的数据对象
                     scope.row.date //是对象里面的data属性的值 -->
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    round
                    v-if="scope.row.orderStatus == 1"
                    @click="orderPay(scope.row)"
                    >去支付</el-button
                  >
                  <el-button
                    size="mini"
                    type="warning"
                    round
                    v-if="scope.row.orderStatus == 5"
                    @click="$refs.appraise.openEditForm(true, scope.row)"
                    >去评价</el-button
                  >

                  <el-button
                    size="mini"
                    type="warning"
                    round
                    v-if="
                      scope.row.orderStatus == 2 && scope.row.appraise == null
                    "
                    @click="$refs.appraise.openEditForm(true, scope.row)"
                    >去评价</el-button
                  >
                  <el-button
                    size="mini"
                    type="success"
                    disabled
                    round
                    v-if="
                      scope.row.orderStatus == 2 && scope.row.appraise != null
                    "
                    >已完成</el-button
                  >
                  <el-button
                    size="mini"
                    type="success"
                    disabled
                    round
                    v-if="
                      scope.row.orderStatus == 6 && scope.row.appraise != null
                    "
                    >已完成</el-button
                  >
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页组件 -->
            <el-col>
              <el-pagination
                background
                @size-change="handlePageSizeChange"
                @current-change="handleCurrentPageChange"
                :current-page="page.currentPage"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="page.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.total"
                align="center"
              >
              </el-pagination>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 租房订单评价表 -->
    <Appraise ref="appraise" @afterSubmit="afterSubmitHandle()"></Appraise>
    <!-- 续房 -->
    <Continue ref="continue" @afterSubmit="afterSubmitHandle()"></Continue>
  </div>
</template>

<script>
import Appraise from "@/views/HousingOrder/appraise";
import Continue from "./continue";

import {
  DateTimeRange_Picker_Option,
  DateRange_Picker_Option,
  Date_Picker_Option,
} from "@/utils/datePicker";

export default {
  name: "housingOrderManage",
  components: {
    Appraise,
    Continue,
  },

  data() {
    return {
      testList: [
        "http://localhost:8080/image/2022-04/72fa59a0-d58b-4b76-966e-639013d92a44.jpeg",
        "http://localhost:8080/image/2022-04/09192289-e267-429e-b4ef-2319844526cd.jpeg",
        "http://localhost:8080/image/2022-04/9c02c2ad-efcc-4f71-b31a-d119464a4800.jpg",
      ],
      // 分页参数
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      // 【租房订单】数据表
      tableData: [],
      // 【租房订单】表已选 IDs
      tableCheckIds: [],
      // 数据加载
      requestLoading: false,
      // 查询表单参数
      queryForm: {
        id: null,
        houseId: null,
        houseOwner: null,
        mealId: null,
        isNeedMeal: null,
        orderStartTime: null,
        orderEndTime: null,
        housingDay: null,
        mealCost: null,
        houseCost: null,
        totalCost: null,
        starMark: null,
        appraise: null,
        reply: null,
        orderStatus: null,
        organizationId: null,
        createUser: null,
        createUserName: null,
        createTime: null,
        updateUser: null,
        updateUserName: null,
        updateTime: null,
      },
      // 日期选择快捷方式
      DateTimeRange_Picker_Option,
      DateRange_Picker_Option,
      Date_Picker_Option,
    };
  },

  // 组件创建时
  created() {
    // 页面元素初始化
  },

  // 组件挂载时
  mounted() {
    this.queryDataBtn();
  },

  methods: {
    // 表单提交后置处理
    afterSubmitHandle() {
      this.queryHousingOrderApi();
      this.tableCheckIds = [];
    },

    // 处理表格行多选
    handleTableRowsSelect(val) {
      let ids = [];
      val.forEach((obj) => ids.push(obj.id));
      this.tableCheckIds = ids;
    },

    // 处理表格行单选
    handleTableCurrentRowChange(row, oldRow) {},

    // ---------------- 分页参数处理 START-----------------
    handleCurrentPageChange(val) {
      this.page.currentPage = val;
      // 查询【租房订单】表
      this.queryHousingOrderApi();
    },
    handlePageSizeChange(val) {
      this.page.pageSize = val;
      this.page.currentPage = 1;
      // 查询【租房订单】表
      this.queryHousingOrderApi();
    },
    // ---------------- 分页参数处理 END-----------------

    // 查询【租房订单】
    queryDataBtn() {
      this.page.currentPage = 1;
      this.queryHousingOrderApi();
    },

    // 查询参数处理
    queryParamProcess() {
      let param = Object.assign({}, this.queryForm);
      param["pageNum"] = this.page.currentPage;
      param["pageSize"] = this.page.pageSize;

      if (this.queryForm.orderStartTime) {
        param["orderStartTimeStart"] = this.queryForm.orderStartTime[0];
        param["orderStartTimeEnd"] = this.queryForm.orderStartTime[1];
      }
      if (this.queryForm.orderEndTime) {
        param["orderEndTimeStart"] = this.queryForm.orderEndTime[0];
        param["orderEndTimeEnd"] = this.queryForm.orderEndTime[1];
      }
      if (this.queryForm.createTime) {
        param["createTimeStart"] = this.queryForm.createTime[0];
        param["createTimeEnd"] = this.queryForm.createTime[1];
      }
      if (this.queryForm.updateTime) {
        param["updateTimeStart"] = this.queryForm.updateTime[0];
        param["updateTimeEnd"] = this.queryForm.updateTime[1];
      }

      delete param.orderStartTime;
      delete param.orderEndTime;
      delete param.createTime;
      delete param.updateTime;

      return param;
    },

    // 查询【租房订单】API
    queryHousingOrderApi() {
      this.requestLoading = true;

      this.$api
        .queryOwnedHousingOrder(this.queryParamProcess())
        .then((res) => {
          this.tableData = [];
          this.page.total = 0;

          let { status, message, data } = res.data;
          if (status == 200) {
            this.tableData = data.items;
            this.page.total = data.totalNum;
            console.log(res);
          } else if (status == 403) {
            this.$message({
              message: `权限不足！${message}`,
              type: "error",
              center: true,
              duration: 1680,
            });
          } else {
            this.$alert(`暂无数据记录！${message}`, "【租房订单】信息表", {
              type: "info",
              confirmButtonText: "确定",
              callback: (action) => {},
            });
          }

          this.requestLoading = false;
        })
        .catch((err) => {
          this.requestLoading = false;
          console.log(`【租房订单】查询接口发生错误: ${err}`);
        });
    },

    // 订单支付
    orderPay(item) {
      const loading = this.$loading({
        target: document.querySelector(".data-table"),
        lock: true,
        text: "请打开手机扫码支付...",
      });

      this.$api
        .queryOneSysUser(item.houseOwner)
        .then((res) => {
          let { status, message, data } = res.data;
          if (status == 200) {


            let a = window.open('', "_blank","height=600, width=600, top=50, left=50, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no")
            a.document.write(`<!DOCTYPE html><html><body ><img src='${this.$store.state.API_ROOT}${data.duty}' width="600" height="600" /></body></html>`)



            // window.open(
            //   `${this.$store.state.API_ROOT}${data.duty}`,
            //   "_blank",
            //   "height=600, width=600, top=50, left=50, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no"
            // );
          } else if (status == 403) {
            this.$message({
              message: `权限不足！${message}`,
              type: "error",
              center: true,
              duration: 1680,
            });
          } else {
            this.$alert(`暂无数据记录！${message}`, "用户信息", {
              type: "info",
              confirmButtonText: "确定",
              callback: (action) => {},
            });
          }
        })
        .catch((err) => {
          console.log(`【单个用户】查询接口发生错误: ${err}`);
        })
        .finally(() => {
          // 模拟交易效果
          setTimeout(() => {
            loading.close();

            this.$confirm("是否已支付成功?", "提示", {
              confirmButtonText: "确认",
              cancelButtonText: "取消",
              type: "warning",
              showClose: false,
              closeOnClickModal: false,
              closeOnPressEscape: false,
            })
              .then(() => {
                // 保存交易
                this.payConfirmCommit(item);
              })
              .catch(() => {
                this.$message({
                  type: "error",
                  message: "交易已取消！系统核查后已支付的资金将原路返回！",
                });
              });
          }, 1680);
        });
    },

    // 支付确认提交
    payConfirmCommit(item) {
      const loading = this.$loading({
        target: document.querySelector(".data-table"),
        lock: true,
        text: "正在保存交易...",
      });

      this.$api
        .payHousingOrder({ id: item.id })
        .then((res) => {
          let { status, message, data } = res.data;
          if (status == 200) {
            // 刷新表格
            this.queryDataBtn();
            // 提示信息
            this.$message({
              type: "success",
              message: `支付成功！支付金额：￥ ${item.totalCost}`,
              duration: 1680,
            });
          } else if (status == 403) {
            this.$message({
              message: `权限不足！${message}`,
              type: "error",
              center: true,
              duration: 1680,
            });
          } else {
            this.$alert(`交易异常！${message}`, "订单支付", {
              type: "error",
              confirmButtonText: "确定",
              callback: (action) => {},
            });
          }
        })
        .catch((err) => {
          console.log(`【订单支付】接口发生错误: ${err}`);
        })
        .finally(() => {
          loading.close();
        });
    },

    // 退房
    finishHousing(item) {
      this.$confirm("确定退房后将进行结算，该操作不可逆, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          // 发起退房操作
          this.finishHousingApi(item);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "暂不退房！",
          });
        });
    },

    // 退房确认提交
    finishHousingApi(item) {
      const loading = this.$loading({
        target: document.querySelector(".data-table"),
        lock: true,
        text: "正在结算...",
      });

      this.$api
        .finishHousingOrder({ id: item.id })
        .then((res) => {
          let { status, message, data } = res.data;
          if (status == 200) {
            // 刷新表格
            this.queryDataBtn();
            // 提示信息
            this.$message({
              type: "success",
              message: `结算成功！${message}`,
              duration: 1680,
            });
          } else if (status == 403) {
            this.$message({
              message: `权限不足！${message}`,
              type: "error",
              center: true,
              duration: 1680,
            });
          } else {
            this.$alert(`结算异常！${message}`, "退房", {
              type: "error",
              confirmButtonText: "确定",
              callback: (action) => {},
            });
          }
        })
        .catch((err) => {
          console.log(`退房接口发生错误: ${err}`);
        })
        .finally(() => {
          loading.close();
        });
    },
  },
};
</script>

<style lang="scss" scoped>
// 表单布局样式
@import "@/assets/css/form-layout.scss";
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
